<script setup lang="ts">
import { ref, onMounted, toRaw, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import Searchbox from "@/views/components/searchbox/Searchbox.vue";
import AddDeviceGroup from './component/add.vue';
import EditDeviceGroup from './component/edit.vue';
import { getDeviceGroupListApi, deleteDeviceGroupApi, DeviceGroupModel } from "@/api/products/deviceGroup";
import { useLogic } from "@/views/system/user/logic/logic";
import { buildTree } from '@/utils/helper';
import { pageSizeOptions } from "@/utils/appCommon/appCommonOptions/app";
import { getGroupPurposeOptions } from '@/utils/appCommon/appCommonOptions/deviceGroup'
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
// 引入关联场景组件
import BindGroupToScene from "@/views/alerts/scene/component/bind-group-to-scene.vue";

//一定要和服务端的权限名称一样
defineOptions({
  name: "devicegroup-manage"
});

const {deptTreeList,getDeptTree}  = useLogic()
onMounted(async () => {
  await getDeptTree()
})

const { t } = useI18n();
const pageSizeOps = ref(pageSizeOptions)

// 搜索处理 - 增加搜索参数存储
const searchParams = ref({
  name:undefined,
  deptId: undefined,
  timeRange: [],
  page:1,
  pageSize: 10,
});
// 搜索字段配置 - 根据设备分组表结构更新
const searchFields = ref([
  {
    prop: "name",
    name: t("products.deviceGroupPage.searchByName"),
    type: "input",
    placeholder: t("products.deviceGroupPage.searchPlaceholder")
  },
  {
    prop: 'timeRange',
    name: t("buttons.timeRange"),
    type: 'datetimeRange',
    clearable: true,
    isHidden: false,
  },
  {
    prop: 'deptId',
    name: t("products.deviceGroupPage.dept"),
    type: 'cascader',
    cascaderOptions: deptTreeList,
    ops: {
      valueField: 'id',
      labelField: 'name',
      emitPath: false,
      checkStrictly: true
    }
  },
]);

// 设备分组列表数据
const deviceGroupList = ref<any[]>([]);
const flatDeviceGroupList = ref<any[]>([]); // 存储原始扁平化数据
const total = ref(0);

// 计算树形结构数据
const treeDeviceGroupList = computed(() => {
  return buildTree(flatDeviceGroupList.value, 'id', 'parentId', 'children');
});

// 加载设备分组列表
const loadDeviceGroupList = async () => {
  try {
    const response = await getDeviceGroupListApi({
      ...searchParams.value
    });

    if (response.code === 0) {
      flatDeviceGroupList.value = response.data?.list || [];
      deviceGroupList.value = treeDeviceGroupList.value; // 使用树形结构数据
      total.value = response.data?.total || 0;
    } else {
      ElMessage.error(response.msg || '获取设备分组列表失败');
    }
  } catch (error) {
    total.value = 0
    ElMessage.error('获取设备分组列表失败');
    console.error('Failed to load device group list:', error);
  }
};

const  handleChange = (e: any) => {
  Object.keys(e).forEach(key => {
    searchParams.value[key] = e[key];
  });
}
const handleSearch = async (e:any) => {
  searchParams.value.page = 1
  Object.keys(e).forEach(key => {
    searchParams.value[key] = e[key];
  });
  await  loadDeviceGroupList();
}
const handleReset = (e:any) => {
}

// 分页变化处理
const handlePaginationSizeChange = (pageSize: number) => {
  console.log(pageSize);
  searchParams.value.pageSize = pageSize;
  loadDeviceGroupList();
};
const handlePaginationPageChange = (page: number) => {
  console.log(page);
  searchParams.value.page = page;
  loadDeviceGroupList();
};

// 初始加载
onMounted(() => {
 loadDeviceGroupList();
});

// 弹窗控制变量
const addDialogVisible = ref(false);
const editDialogVisible = ref(false);
const currentGroup = ref<any>(null);
// 关联场景对话框控制
const bindSceneDialogVisible = ref(false);
const currentBindGroup = ref<DeviceGroupModel | any>({});

// 打开新增弹窗
const openAddDialog = () => {
  addDialogVisible.value = true;
};

// 删除设备分组
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm(
      t('products.deviceGroupPage.confirmDelete'),
      t('products.deviceGroupPage.confirmTitle'),
      {
        confirmButtonText: t('buttons.confirm'),
        cancelButtonText: t('buttons.cancel'),
        type: 'warning'
      }
    );

    const response = await deleteDeviceGroupApi(id);
    if (response.code === 0) {
      ElMessage.success(t("products.deviceGroupPage.deleteSuccess"));
      await loadDeviceGroupList();
    } else {
      ElMessage.error(response.msg || t("products.deviceGroupPage.deleteFailed"));
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(t("products.deviceGroupPage.deleteFailed"));
      console.error('Failed to delete device group:', error);
    }
  }
};

// 打开编辑弹窗
const openEditDialog = (row: any) => {
  currentGroup.value = { ...row };
  editDialogVisible.value = true;
};

// 打开关联场景对话框
const handleBindScene = (row: DeviceGroupModel) => {
  currentBindGroup.value = row;
  bindSceneDialogVisible.value = true;
};

// 处理新增成功
const handleAddSuccess = () => {
  addDialogVisible.value = false;
  loadDeviceGroupList(); // 新增成功后刷新列表
};

// 处理编辑成功
const handleEditSuccess = () => {
  editDialogVisible.value = false;
  loadDeviceGroupList(); // 编辑成功后刷新列表
};

// 处理关联场景成功
const handleBindSceneSuccess = () => {
  bindSceneDialogVisible.value = false;
};

// 加载子分组数据
const loadChildGroups = (row: any, treeNode: any, resolve: (data: any[]) => void) => {
  // 查找当前节点的所有子节点
  const children = flatDeviceGroupList.value.filter(item => item.parentId === row.id);
  // 为每个子节点标记是否有子节点
  const childrenWithFlag = children.map(child => ({
    ...child,
    hasChildren: flatDeviceGroupList.value.some(item => item.parentId === child.id)
  }));
  resolve(childrenWithFlag);
};
const purposeOptions = ref<Array<{ val: string; label: string }>>([])

// 初始化数据
onMounted(async () => {
  // 获取用途选项
  purposeOptions.value = await getGroupPurposeOptions()
})

// 获取用途的中文标签
const getPurposeLabel = (value: string) => {
  const option = purposeOptions.value.find(item => item.val === value)
  return option ? option.label : value
}

const router = useRouter();
const goToConfig = (deviceGroupId: number) => {
  router.push({
    path: '/configs/deviceGroupConfig',
    query: { deviceGroupId }
  });
};


</script>

<template>
  <el-card shadow="never">
    <template #header>
      <div class="card-header">
        <Searchbox
          :fields= searchFields
          :initialValues="searchParams"
          :maxVisibleFields=1
          @change="handleChange"
          @search="handleSearch"
          @reset="handleReset"
        />
      </div>
    </template>

    <!-- 按钮区 -->
    <div class="button-area">
      <el-button
        type="primary"
        icon="Plus"
        @click="openAddDialog"
      >
        {{ t("products.deviceGroupPage.addGroup") }}
      </el-button>
    </div>

    <!-- 设备分组分页表格 -->
    <div class="table-container">
      <el-table
        :data="deviceGroupList"
        border
        stripe
        style="width: 100%"
        :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }"
        row-key="id"
        lazy
        :load="loadChildGroups"
        :tree-props="{ hasChildren: 'hasChildren', children: 'children' }"
      >
        <el-table-column prop="id" :label="'ID'" width="70" />
        <el-table-column prop="groupKey" :label="t('products.deviceGroupPage.groupKey')" min-width="120" />
        <el-table-column prop="name" :label="t('products.deviceGroupPage.groupName')" min-width="120">
          <template #default="{ row }">
            <div style="display: flex; align-items: center;">
              <span>{{ row.name }}</span>
              <el-tag v-if="row.parentId !== 0" size="small" type="info" style="margin-left: 10px;">
                {{ t("products.deviceGroupPage.childGroup") }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="purpose" :label="t('products.deviceGroupPage.purpose')" min-width="100">
          <template #default="scope">
            {{ getPurposeLabel(scope.row.purpose) }}
          </template>
        </el-table-column>
        <el-table-column prop="deptName" :label="t('products.deviceGroupPage.deptName')" min-width="120" />
        <el-table-column prop="createdAt" :label="t('products.deviceGroupPage.createdAt')" min-width="160" />
        <el-table-column :label="t('products.deviceGroupPage.operation')" min-width="180">
          <template #default="{ row }">
            <el-button type="primary" size="small" plain @click="openEditDialog(row)">{{ t("buttons.edit") }}</el-button>
            <el-button size="small" plain @click="handleBindScene(row)">{{ t("alerts.sceneOperatePage.bindScene") }}</el-button>
            <el-button type="danger" size="small" plain @click="handleDelete(row.id)">{{ t("buttons.delete") }}</el-button>
            <el-button type="info" size="small" plain @click="goToConfig(row.id)">{{ t("products.deviceGroupPage.configGroup") }}</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="searchParams.page"
          v-model:page-size="searchParams.pageSize"
          :page-sizes="pageSizeOps"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handlePaginationSizeChange"
          @current-change="handlePaginationPageChange"
        />
      </div>
    </div>
    <!-- 新增设备分组弹窗 -->
    <AddDeviceGroup
      v-model:visible="addDialogVisible"
      @success="handleAddSuccess"
    />
    <!-- 编辑设备分组弹窗 -->
    <EditDeviceGroup
      v-model:visible="editDialogVisible"
      :group="currentGroup"
      @success="handleEditSuccess"
    />

    <!-- 关联场景对话框 -->
    <BindGroupToScene
      v-model:visible="bindSceneDialogVisible"
      :device-group-id="currentBindGroup.id"
      :dept-id="currentBindGroup.deptId"
      @success="handleBindSceneSuccess"
    />
  </el-card>
</template>

<style scoped lang="scss">
.table-container {
  margin-top: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
  padding: 10px;
}

.button-group {
  display: flex;
  gap: 10px;
}
</style>


